<template>
    <el-row class="row-wrapped">
        <el-col :span="12" class="ImageUrl"></el-col>
        <el-col :span="12" class="table-content">
            <el-card class="box-card">
                <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
                    class="demo-ruleForm" v-show="flag">
                    <el-form-item style="align-items: center;">
                        <h3>登录界面</h3>
                    </el-form-item>
                    <el-form-item label="账号:" prop="username">
                        <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="密码:" prop="password">
                        <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button size="medium" type="primary" @click="submitForm('ruleForm')">登录</el-button>
                        <el-button size="medium" @click="resetForm('ruleForm')">重置</el-button>
                    </el-form-item>
                    <el-form-item>
                        <span>还没注册？<el-button type="text" size="medium" @click="flag = false">马上注册</el-button></span>
                    </el-form-item>
                </el-form>
                <el-form :model="registerForm" status-icon :rules="registerRules" ref="registerForm" label-width="100px"
                    class="demo-ruleForm" v-show="!flag">
                    <el-form-item style="align-items: center;">
                        <h3>注册界面</h3>
                    </el-form-item>
                    <el-form-item label="账号:" prop="username">
                        <el-input type="text" v-model="registerForm.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="密码:" prop="password">
                        <el-input type="password" v-model="registerForm.password" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="验证码:" prop="code">
                        <div class="code">
                            <el-input placeholder="请输入验证码"  size="medium" autocomplete="off"
                                style="flex: 1" v-model="registerForm.code"></el-input>
                            <div style="flex: 1; height: 36px">
                                <!--是一个自定义组件ValidCode的使用方式，并且添加了一个事件监听器。这里的@update:value是监听了ValidCode组件中的value属性更新事件，并将更新后的值传递给名为getCode的方法。
当ValidCode组件中的value属性更新时，会触发getCode方法。getCode方法可在父组件中定义，用于处理接收到的验证码信息或进行相关操作。-->
                                <valid-code @update:value="getCode"/>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-button size="medium" type="primary" @click="register('registerForm')">注册</el-button>
                        <el-button size="medium" @click="resetForm('registerForm')">重置</el-button>
                    </el-form-item>
                    <el-form-item>
                        <span>已有帐号？<el-button type="text" size="medium" @click="flag = true">马上登录</el-button></span>
                    </el-form-item>
                </el-form>
            </el-card>
        </el-col>
    </el-row>
</template>

<script>
import { UserLoginServer, OnlyUserServer, RegisterUserServer } from '@/api/user';
import ValidCode from '@/components/ValidCode.vue';
export default {
    components: {
        ValidCode
    },
    data() {
        // 验证码校验
        let validateCode = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入验证码'))
            } else if (value.toLowerCase() !== this.code) {
                callback(new Error('验证码错误'))
            } else {
                callback()
            }
        }
        //自定义用户名唯一验证
        let onlyUserName = async (rule, value, callback) => {
            let res = await OnlyUserServer(value)
            if (res.code == 0) {
                callback(new Error("用户名已存在"))
            } else {
                callback();
            }
        }
        return {
            flag: true,
            ruleForm: {
                username: '',
                password: '',
            },
            registerForm: {
                username: '',
                password: '',
                code: '',
            },
            code:'',
            rules: {
                username: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入账号密码', trigger: 'blur' },
                    { min: 3, max: 8, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
            },
            registerRules: {
                username: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
                    { validator: onlyUserName, message: '用户名已存在', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入账号密码', trigger: 'blur' },
                    { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    { validator: validateCode, message: '验证码不正确', trigger: 'blur' }
                ],
            },
        };
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    let res = await UserLoginServer(this.ruleForm)
                    if (res.code == 1) {
                        // this.$store.commit('setToken', res.data.token)
                        // 存储令牌到 localStorage
                        localStorage.setItem('token', res.data.token);
                        this.$message({
                            showClose: true,
                            message: '登陆成功',
                            type: 'success'
                        });
                        this.$router.push('/home')
                    } else {
                        this.$message({
                            showClose: true,
                            message: '用户或者密码有误',
                            type: 'error'
                        });
                    }

                } else {
                    this.$message({
                        showClose: true,
                        message: '信息填写有误',
                        type: 'error'
                    });
                    return false;
                }
            });
        },
        getCode(code) {
          this.code = code.toLowerCase()
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        register(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    let res = await RegisterUserServer(this.registerForm)
                    if (res.code == 1) {
                        this.$message({
                            showClose: true,
                            message: '注册成功',
                            type: 'success'
                        });
                        this.flag = true
                    } else {
                        this.$message({
                            showClose: true,
                            message: '注册失败',
                            type: 'error'
                        });
                    }
                }
            });
        }
    }
}
</script>

<style lang="less" scoped>
.row-wrapped {
    height: 100vh;
    width: 100%;
    display: flex;
    flex-direction: row;
    overflow: hidden;

    .ImageUrl {
        display: flex;
        height: 100vh;
        width: 50%;
        background-image: url('@/assets/R.jpg');
        background-size: 90% 80%;
        /* 或使用 contain, 100px 50px, 50% 50% 等 */
        background-position: center;
        /* 可选：将背景图片定位于容器中心 */
        background-repeat: no-repeat;
    }

    .table-content {
        display: flex;
        height: 100vh;
        width: 50%;
    }
}

.el-col {
    border-radius: 4px;
}

.el-form {
    width: auto;
    display: flex;
    flex-direction: column;
    align-items: center;

}
.code{
    display: flex;
}
.box-card {
    width: 480px;
    margin-top: 10%;
    height: 440px;
    border-radius: 10px;
    /* 圆角 */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    /* 添加阴影效果 */

    .el-card__body {
        margin-left: 1%;
    }
}
</style>